<template>
  <div>
    <myDivider name="机构管理"></myDivider>
    <!-- <el-alert :closable="false" title="三级菜单1" type="success" /> -->
    <el-page-header @back="goBack" :content="this.operateType == 'update' ? '修改机构信息' : '新增机构信息'">
    </el-page-header>
    <div class="insertPopulation">
      <el-form ref="insertForm" :model="insertForm" label-width="80px" :inline="true" :rules="insertRules">
        <el-form-item label="名称:" :label-width="formLabelWidth" class="formItemStyle" prop="shortName">
          <el-input placeholder="请输入名称" maxlength="20" v-model="insertForm.shortName" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>

        <!-- <el-form-item label="超级管理员:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="insertForm.superAdministratorId" filterable placeholder="请选择" style="width: 262px;"
            @filter-method="getFatherAgenciesOptionData(name)">
            <el-option v-for="item in superAdministratorIdData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="机构类型:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="insertForm.type" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in fatherAgenciesOptionData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上级机构:" :label-width="formLabelWidth" class="formItemStyle">
          <!-- <el-input v-model="insertForm.parentbody" autocomplete="off" style="width: 262px"></el-input> -->
          <el-select v-model="insertForm.fatherCompanyId" filterable placeholder="请选择" style="width: 682px"
            @filter-method="getFatherAgenciesOptionData(name)">
            <el-option v-for="item in fatherCompanyIdData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>



        <el-form-item label="所在地区:" :label-width="formLabelWidth" class="formItemStyle">
          <!-- <el-input v-model="insertForm.criCode" autocomplete="off" style="width: 500px"></el-input> -->
          <el-cascader ref="areas" v-model="insertForm.criCode" @focus="cascaderClick" :props="props" :options="options"
            @change="handleChange" style="width: 682px"></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input placeholder="请输入详细地址" v-model="insertForm.address" autocomplete="off" style="width: 682px"></el-input>
        </el-form-item>
        <el-form-item label="联系人姓名:" :label-width="formLabelWidth" class="formItemStyle" prop="contactName">
          <el-input placeholder="请输入姓名" maxlength="5" v-model="insertForm.contactName" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>
        <el-form-item label="联系人手机号:" :label-width="formLabelWidth" class="formItemStyle" prop="telephoneNumber">
          <el-input placeholder="请输入手机号" maxlength="15" v-model="insertForm.telephoneNumber" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>
        <el-form-item label="是否认证:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select :disabled="operateType == 'update'" v-model="insertForm.authenticationStatus" filterable
            placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in authenticationStatusData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input placeholder="请输入负责人" maxlength="15" v-model="insertForm.responsiblePersonName" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>
      </el-form>



      <!-- 添加取消 -->
      <el-form ref="form" :model="insertForm" label-width="80px" style="height: 41px;">
        <el-form-item style="float: right; margin-bottom: 80px;">
          <el-button type="primary" @click="onSubmitUpdate" v-if="this.operateType == 'update'">修改</el-button>
          <el-button type="primary" @click="onSubmit" v-if="this.operateType == 'insert'">添加</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>

      <el-divider></el-divider>
    </div>
  </div>
</template>

<style lang="less" scoped>
.szdqBox {
  display: flex;

  .addressStyle {
    width: 350px;
    display: flex;
    justify-content: space-between;
    flex-wrap: nowrap;

    /deep/ label {
      width: 33%;

      select {
        width: 100%;
      }
    }
  }
}


.insertPopulation {
  margin-top: 90px;
  margin-left: 130px;
  height: 50%;
}

.menuTable {
  margin-top: 100px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.menuTable .cell {
  text-align: center;
}

.findValue {
  width: 13%;
  margin-top: 20px;
  margin-left: 15px;
}

.operation {
  margin-right: 50px;
  float: right;
  margin-top: 20px;
}

.formStyle {
  width: 1300px;
  margin: 20px auto;
}

.formItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}

.pageFooter {
  margin-top: 3%;
  margin-left: 40%;
}

.pageFooterFather {
  top: 84%;
  position: relative;
  width: 100%;
}

.el-cascader-menu {
  height: fit-content;
  width: fit-content;
}

.birthdayDateItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}
</style>

<script>
import VDistpicker from 'v-distpicker'
import { getUserList } from "../user/user";
import {
  getFatherAgencies,
  insertAgency,
  getDictionaryList,
  getInDetail,
  updateinstInfo,
  getcityList,
  getShangJiJiGouList
} from "./institution";
export default {
  components: { VDistpicker },
  data() {
    var phonerule = (rule, value, callback) => {
      let pattern = /^1[3456789]\d{9}$/
      if (!value) {
        return callback(new Error('手机号不能为空'));
      } else if (!pattern.test(value)) {
        return callback(new Error('请输入正确手机号'));
      } else {
        return callback()
      }
    }
    return {
      criCodeDefaultShow: true,
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          let { level } = node
          if (level == 0) {
            getcityList('000000').then(res => {
              let arr = []
              res.forEach(el => {
                arr.push({
                  value: el.criCode,
                  label: el.criName,
                })
              })
              resolve(arr)
            })
          } else {
            getcityList(node.value).then(res => {
              res.forEach(el => {
                el.value = el.criCode
                el.label = el.criName
                el.leaf = level >= 3
              })
              resolve(res)
            })
          }


        }
      },
      options: [
        {
          value: '001', label: '河北', 'children': [
            {
              value: '002', label: '石家庄', 'children': [
                {
                  value: '003', label: '裕华区', 'children': [
                    { value: '004', label: '太行大街', }
                  ]
                }
              ]
            }
          ]
        },
        {
          value: '005', label: '湖北', 'children': [
            {
              value: '006', label: '赤壁', 'children': [
                {
                  value: '007', label: '长江', 'children': [
                    { value: '008', label: '友谊大街', }
                  ]
                }
              ]
            }
          ]
        },
      ],

      // 是否认证
      authenticationStatusData: [
        { name: '未认证', id: '0' },
        { name: '已认证', id: '1' },
      ],
      //管理员数据
      superAdministratorIdData: [],
      // 上级机构信息
      fatherCompanyIdData: [],
      formLabelWidth: "120px", //控制前面label的宽度
      criCodeDefault: '',
      insertForm: {
        id: '',
        // 新增弹框参数
        shortName: "",
        superAdministratorId: "",
        type: "",
        fatherCompanyId: "",
        criCode: '',
        contactName: "",
        telephoneNumber: "",
        authenticationStatus: ""
      },
      insertRules: {
        contactName: [
          {
            required: true,
            message: "联系人不能为空",
            trigger: "blur"
          }
        ],
        telephoneNumber: [
          {
            required: true,
            validator: phonerule,
            trigger: 'blur'
          }
        ],
        shortName: [
          {
            required: true,
            message: "设备名称不能为空",
            trigger: "blur"
          }
        ]
      },
      operateType: "insert",
      genderListData: [
        { id: "0", name: "女" },
        { id: "1", name: "男" }
      ],
      fatherAgenciesOptionData: [],
      typeOptionData: [],
      query: {
        name: "",
        account: ""
      },
      pageNum: 0,
      pageSize: 10,
      totalSize: 0
    };
  },

  activated() {
    if (this.$route.query.operateType == "update") {
      this.getAgencyInfo(this.$route.query.id);
      this.operateType = "update";
    } else {
      // this.insertForm = {};
      this.insertForm = {
        id: '',
        // 新增弹框参数
        shortName: "",
        superAdministratorId: "",
        type: "",
        fatherCompanyId: "",
        criCode: '',
        contactName: "",
        address:'',
        telephoneNumber: "",
        authenticationStatus: "",
        responsiblePersonName: '',
      },
        this.operateType = "insert";
    }
    this.getZuZhiLeiXing()
    //刚进入页面加载
    this.getFatherAgenciesOptionData("");
  },
  mounted: function () {
    //初始化选项数据

  },

  methods: {
    //级联选择器获取焦点
    cascaderClick() {
      this.props.lazy = true
      this.options = []
    },
    handleChange(val) {
      console.log(val);
      this.insertForm.criCode = val[val.length - 1]
    },
    /**
     *  新增
     */
    onSubmit() {
      console.log(this.insertForm, '新增信息');
      let that = this
      this.$refs['insertForm'].validate((valid) => {
        if (valid) {
          insertAgency(that.insertForm).then(res => {
            console.log(res, '新增接口返回信息');
            if (res.code == 200) {
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.goBack();
            } else {
              if (res.message == '值重复') res.message = '机构名称不能重复'
              this.$message({
                message: res.message,
                type: "warning"
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    /**
     *  修改
     */
    onSubmitUpdate() {
      // 如果用户未修改地址
      if (!this.props.lazy) {
        this.insertForm.criCode = this.insertForm.criCode[this.insertForm.criCode.length - 1]
      }
      console.log(this.insertForm, '修改信息');
      this.insertForm.id = this.$route.query.id;
      updateinstInfo(this.insertForm).then(res => {
        if (res.code == 200) {
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.goBack();
        } else {
          this.$message({
            message: res.message,
            type: "warning"
          });
        }
      });
    },

    /**
     *  上一页
     */
    goBack() {
      // this.$router.push({ path: "/institution/inManagement" });
      this.$router.back(-1)
    },

    /**
     * 获取type类型
     */
    async getFatherAgenciesOptionData(name) {
      this.fatherCompanyIdData = []
      // 上级机构信息
      let ShangJiJiGouList = await getShangJiJiGouList()
      console.log(ShangJiJiGouList, '上级机构列表');
      ShangJiJiGouList.forEach(el => {
        this.fatherCompanyIdData.push({
          name: el.shortName,
          type: el.id
        })
      })
      this.fatherCompanyIdData.unshift({
        name: '无',
        type: 0
      })
      // 机构type类型获取
      this.fatherAgenciesOptionData = [
        { name: "物业公司", type: '1' },
        { name: "其他机构", type: '2' }
      ];


      // 获取管理员信息
      this.superAdministratorIdData = [
        { name: '超级管理员', type: 0 },
        { name: '普通管理员', type: 1 }
      ]
    },
    dgfun(res) {
      let arr = []
      res.forEach(el => {
        // 如果有孩子们，继续遍历
        if (el.childrenList != null) {
          el.childrenList = this.dgfun(el.childrenList)
        }
        arr.push({
          value: el.criCode,
          label: el.criName,
          children: el.childrenList,
        })
      })
      return arr
    },
    getZuZhiLeiXing() {
      getDictionaryList("agency_type").then(res => {
        this.typeOptionData = res.data;
      });
    },
    /**
     * 获取类型字典数据
     */


    getAgencyInfo(id) {
      getInDetail(id).then(async res => {
        console.log(res);
        // 先不让级联选择器设置为搜索
        this.props.lazy = false
        // 挨个通过code值寻找下级孩子
        let arr = ['000000', res.provinceCriCode, res.cityCriCode, res.districtCriCode, res.criCode]
        let res1 = await getcityList(arr[0])
        let res2 = await getcityList(arr[1])
        let res3 = await getcityList(arr[2])
        let res4 = await getcityList(arr[3])
        let res5 = await getcityList(arr[4])
        this.options = []
        res1.forEach(el => {
          this.options.push({
            value: el.criCode,
            label: el.criName,
            children: [],
          })
        })
        this.options.forEach(el => {
          if (el.value == arr[1]) {
            res2.forEach(item => {
              el.children.push({
                value: item.criCode,
                label: item.criName,
                children: [],
              })
            })
            el.children.forEach(dsc => {
              if (dsc.value == arr[2]) {
                res3.forEach(item => {
                  dsc.children.push({
                    value: item.criCode,
                    label: item.criName,
                    children: [],
                  })
                })
              }
              dsc.children.forEach(dsic => {
                if (dsic.value == arr[3]) {
                  res4.forEach(item => {
                    dsic.children.push({
                      value: item.criCode,
                      label: item.criName,
                    })
                  })
                }
              })
            })
          }
        })

        this.criCodeDefault = true
        this.criCodeDefault = res.areaName
        this.insertForm = {
          shortName: res.shortName,
          superAdministratorId: res.superAdministratorId,
          type: res.type,
          fatherCompanyId: res.fatherCompanyId,
          criCode: [res.provinceCriCode, res.cityCriCode, res.districtCriCode, res.criCode],
          // criCode: ['130000', '130100', '130102', "130102003"],
          contactName: res.contactName,
          address:res.address,
          telephoneNumber: res.telephoneNumber,
          authenticationStatus: res.authenticationStatus,
          responsiblePersonName: res.responsiblePersonName,
        }
        console.log(this.insertForm, '详情信息');
      });
    },


  }
};
</script>
